package designpatterns.structure;

/**
 * 适配器模式
 * 将一个类的接口转换成客户希望的另外一个接口，使得原本由于接口不兼容而不能一起工作的那些类能一起工作
 * 优点：客户端通过适配器可以透明地调用目标接口。
 * 复用了现存的类，不需要修改原有代码而重用现有的适配者类。
 * 缺点：对类适配器来说，更换适配器的实现过程比较复杂
 *
 * @author jack.wu
 * @since 2019/9/20
 */
public class AdapterTest {

    public static void main(String[] args) {
        MediaPlayer player = new AudioPlayer();
        player.play("mp3","i miss u.mp3");
        player.play("mp4","i miss u.mp4");
        player.play("vlc","i miss u.vlc");
        player.play("xxx","i miss u.xxx");
    }

}

interface MediaPlayer {
    void play(String audioType, String fileName);
}

interface AdvancedMediaPlayer {

    void playVlc(String fileName);

    void playMp4(String fileName);
}

class VlcPlayer implements AdvancedMediaPlayer {

    @Override
    public void playVlc(String fileName) {
        System.out.println("Playing vlc file. Name:" + fileName);
    }

    @Override
    public void playMp4(String fileName) {

    }
}

class Mp4Player implements AdvancedMediaPlayer {

    @Override
    public void playVlc(String fileName) {

    }

    @Override
    public void playMp4(String fileName) {
        System.out.println("Playing Mp4 file. Name:" + fileName);
    }
}

class MediaAdapter implements MediaPlayer {

    private AdvancedMediaPlayer advancedMediaPlayer;

    public MediaAdapter(String audioType) {

        switch (audioType) {
            case "vlc":
                advancedMediaPlayer = new VlcPlayer();
                break;
            case "mp4":
                advancedMediaPlayer = new Mp4Player();
                break;
            default:
                advancedMediaPlayer = null;
                break;
        }
    }

    @Override
    public void play(String audioType, String fileName) {
        switch (audioType) {
            case "vlc":
                advancedMediaPlayer.playVlc(fileName);
                break;
            case "mp4":
                advancedMediaPlayer.playMp4(fileName);
                break;
            default:
                break;
        }
    }
}

class AudioPlayer implements MediaPlayer {

   private MediaAdapter mediaAdapter;

    @Override
    public void play(String audioType, String fileName) {
        if ("mp3".equalsIgnoreCase(audioType)) {
            System.out.println("Playing mp3 file. name:" + fileName);
        } else if ("vlc".equalsIgnoreCase(audioType) || "mp4".equalsIgnoreCase(audioType)) {
            mediaAdapter = new MediaAdapter(audioType);
            mediaAdapter.play(audioType, fileName);
        }else {
            System.out.println("Not supported given music file");
        }
    }
}
